import { invoke } from "@tauri-apps/api";
import { Dialog } from "../utils/ui";
import { appWindow } from "@tauri-apps/api/window";

export async function debugInfo() {
    return await invoke('debug_info') as string[];
}

const EVENT_DOWNLOAD_INIT = "download_init";
const EVENT_DOWNLOAD_PROG = "download_prog";
const EVENT_DOWNLOAD_ERASE = "download_erase";

export interface ProgInfo {
    size: number,
    duration: number,
}

export async function reset(id: string) {
    
}

export async function chipFamilies() {
    const n = await invoke('chip_families');
    console.log(n);
}

export async function download(id: string, file_path: string, target: string, dialog: Dialog) {

    let file_size: number | null = null;
    let prog_index = 0;
    let erase_index = 0;
    let progLn = await appWindow.listen<ProgInfo>(EVENT_DOWNLOAD_PROG, (e) => {
        const info = e.payload;
        if (file_size == null) {
            return;
        }
        const fs = file_size as number;
        prog_index += info.size;
        let prog = prog_index * 100 / fs;
        dialog.setMsg(`编程进度:${ Math.floor(prog)  }%`);
    });
    let initLn = await appWindow.listen<number>(EVENT_DOWNLOAD_INIT, (e) => {
        file_size = e.payload;
    });
    let eraseLn = await appWindow.listen<ProgInfo>(EVENT_DOWNLOAD_ERASE, (e) => {
        erase_index += e.payload.size;
        dialog.setMsg(`扇区擦除:${erase_index / 1024}KB`);
    });

    try {
        await invoke('download', {
            id,
            filePath: file_path,
            target: target
        });
    } catch (e) {
        throw e
    } finally {
        progLn();
        initLn();
        eraseLn();
    }
}